package org.example.seri

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import java.security.Key;
import java.util.Date;

class T2 {

    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            println(JwtUtil.SECRET_KEY.format)
            val token = JwtUtil.generateToken("123456789", "zjn")
            println(token)
            println("长度 ${token.length}")
            val l = System.currentTimeMillis()

            for (i in 1..1000000) {
                val validateToken = JwtUtil.validateToken(token)
                val expired = JwtUtil.isTokenExpired(token)
//            println(expired)
            }
            println("耗时 ${System.currentTimeMillis() - l}")
            println("success")
        }

    }
}

object JwtUtil {
    // 用于签名的密钥（生产环境中应该从配置文件或环境变量读取）
//    val SECRET_KEY: Key = Keys.secretKeyFor(SignatureAlgorithm.HS256)
    val SECRET_KEY: Key = Keys.hmacShaKeyFor("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx".encodeToByteArray())

    // Token 有效期（毫秒）
    const val EXPIRATION_TIME: Long = 86400000 // 24小时

    // 缓存 parser 实例
    private val jwtParser = Jwts.parserBuilder().setSigningKey(SECRET_KEY).build()
    // 生成 Token
    fun generateToken(userId: String?, username: String?): String {
        val now = Date()
        val expiryDate = Date(now.time + EXPIRATION_TIME)

        return Jwts.builder()
            .setSubject(userId)
            .setIssuedAt(now)
            .setExpiration(expiryDate)
            .signWith(SECRET_KEY, SignatureAlgorithm.HS256)
            .compact()
    }

    // 验证 Token
    fun validateToken(token: String?): Boolean {
        try {
            jwtParser.parseClaimsJws(token)
            return true
        } catch (e: JwtException) {
            // Token 无效
            return false
        } catch (e: IllegalArgumentException) {
            return false
        }
    }

    // 从 Token 中获取用户 ID
    fun getUserIdFromToken(token: String?): String {
        val claims: Claims = jwtParser
            .parseClaimsJws(token)
            .getBody()

        return claims.getSubject()
    }

    // 检查 Token 是否过期
    fun isTokenExpired(token: String?): Boolean {
        val expiryDate: Date = jwtParser
            .parseClaimsJws(token)
            .getBody()
            .getExpiration()

        return expiryDate.before(Date())
    }
}

